<template>
  <div class="view-wrapper">
    <div class="configVersion">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm"
        v-loading="loading">
        <el-form-item label="版本号：" prop="edition">
          <el-input v-model="ruleForm.edition" placeholder="请输入版本号" style="width:90%"></el-input>
        </el-form-item>
        <el-form-item label="版本名称：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入版本名称" style="width:90%"></el-input>
        </el-form-item>
        <el-form-item label="升级内容：" prop="content">
          <el-input
            type="textarea"
            :rows="8"
            placeholder="请输入内容"
            v-model="ruleForm.content">
          </el-input>
        </el-form-item>
        <el-form-item label="上传安装包：" prop="url" ref="urlRef">
            <el-upload class="upload-demo" :action="fileaction" :headers="headers"  :limit="1" 
              :on-success="handleFileChange" :before-upload="beforeAvatarUpload" :show-file-list="true" :file-list="fileList" :on-remove="onRemove">
              <el-button type="primary" size="small">上传安装包</el-button>
              <div slot="tip" class="el-upload__tip">只能上传apk文件</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="是否强制更新：" prop="isUpdate">
          <el-switch
            v-model="ruleForm.isUpdate"
            active-value="2" 
            inactive-value="1"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item>
            <!-- <el-button @click="handleClose">取 消</el-button> -->
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="submitLoading">确 定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import {
    editKyyVersion,
    kyyVersionDetail,
  } from "@/api/setting/configVersion";
  import Loading from "@/components/Loading/index";
  import Editor from '@/components/Editor';
  // api
  import {
    getToken
  } from "@/utils/auth";
  export default {
    components: {
      Loading,
      Editor,
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      const fileMustUpload = (rule, value, callback) => {
        if (this.ruleForm.url == '') {
          // 未上传文件
          callback("请上传文件");
        }
        callback();
      }
      return {
        title: '新建区域',
        loading: false,
        submitLoading: false,
        formInline: {
          name: "", //区域名称
        },
        title: '添加区域', //
        props: {
          multiple: true
        },
        fileList: [],
        fileaction: process.env.VUE_APP_BASE_API + "/common/v1/uploadSetFileName",
        headers: {
          "X-Access-Token": getToken(),
        }, //设置上传文件请求头
        ruleForm: {
          content: '',//	升级内容
          edition: '',//	版本号
          id: '',//	主键id
          isUpdate: '1',//	是否强制更新 1 否 2 是
          name: '',//	版本名称
          url: '',//	下载url
        },
        rules: {
          edition: [{
            required: true,
            message: "请输入版本号",
            trigger: ['blur', 'change']
          }, ],
          name: [{
            required: true,
            message: "请输入区域名称",
            trigger: ['blur', 'change']
          }, ],
          isUpdate: [{
            required: true,
            message: "请选择",
            trigger: "blur"
          }],
          content: [{
            required: true,
            message: "请输入升级内容",
            trigger: ['blur', 'change']
          }, ],
          url: [{
            required: true,
            validator: fileMustUpload,
            trigger: [ 'change']
          }, ],
        },
        editId: '', //编辑id
      
      };
    },
    computed: {},
    created() {
      this.getInfo()
   
    },
    methods: {
      handleCityChange(array) {
        console.log(array)
      },
      getInfo() { //获取信息详情
        this.loading = true
        var id = 1
        kyyVersionDetail(id).then((res) => {
            this.ruleForm = res.result
            this.fileList = []
            var obj = {}
            obj.name = res.result.name
            obj.url = res.result.url
            this.fileList.push(obj) 
            setTimeout(() => {
              this.loading = false;
            }, 800)
          })
          .finally(() => {
            setTimeout(() => {
              this.loading = false;
            }, 800)
          });
      },
       //导入文件
      handleFileChange(res, file) {
        
        if (res.code == 200) {
          this.$message.success('上传成功');
          this.ruleForm.url = res.result.url
          this.loading = false
          this.$refs['urlRef'].clearValidate();
        } else {
          this.$message.error(res.msg);
          this.fileList = []
          this.loading = false
        }
      },
      beforeAvatarUpload(file) {
        this.loading = true
        console.log('file',file)
        const isAPK = file.type === 'application/vnd.android.package-archive';
        if (!isAPK) {
          this.$message.error('上传文件只能是 apk 格式!');
          this.loading = false;
        }
        return isAPK 
      },
      onRemove(res){
        this.fileList = []
        this.ruleForm.url = ''
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var params = {
              ...this.ruleForm
            };
            this.submitLoading = true
            editKyyVersion(params).then((res) => {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                this.getInfo()
                setTimeout(() => {
                  this.$emit('success')
                  this.submitLoading = false
                }, 1000);
              })
              .catch(() => {
                setTimeout(() => {
                  this.getInfo()
                  this.submitLoading = false;
                }, 800)
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.ruleForm.areaList.length > 0) {
              var areaList = []
              this.ruleForm.areaList.forEach(item => {
                var obj = {}
                obj.province = item[0]
                obj.city = item[1]
                obj.area = item[2]
                areaList.push(obj)
              })
            }
            var params = {
              name: this.ruleForm.name,
              sort: this.ruleForm.sort,
              areaList: areaList,
              id: this.id,
            };
            this.submitLoading = true
            editArea(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.getInfo()
                setTimeout(() => {
                  this.submitLoading = false
                }, 1000);
              })
              .catch(() => {
                setTimeout(() => {
                  this.getInfo()
                  this.submitLoading = false;
                }, 800)
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
.configVersion{
  background: #fff;
  padding: 20px;
}
.el-input{
  width: 240px !important;
}
</style>
